<script setup>
import InputText from "../components/InputText.vue";

import Button from "../components/Button.vue";
import IconSvg from "../components/IconSvg.vue";
import DataTable from "../components/DataTable.vue";
import Message from "../components/Message/Message.js";
import PaginationBasic from "../components/PaginationBasic.vue";
import Textarea from "../components/Textarea.vue";
import InputCheckbox from "../components/InputCheckbox.vue";
import Flow from "../components/Flow.vue";
import TextDivider from "../components/TextDivider.vue";
import { ref, onMounted } from "vue"
import axios from "../axios/axios.js";
const searchInfo = ref({ processName: '' });

const defaultIds = ref([])
const isOperate = ref(false)
const isAdd = ref(false)
const currentIndex = ref(0)
const addInfo = ref({})
const pageData = ref({
  currentPage: 1,
  total: 0,
  pageSize: 10,
})
const procedurePageData = ref({
  currentPage: 1,
  total: 0,
  pageSize: 10,
})

// 页码变化时触发
const handlePageChange = (page) => {
  pageData.value.currentPage = page
  // 这里可以调用接口加载对应页的数据
  getData()
}
const handlePageProcessChange = (page) => {
  procedurePageData.value.currentPage = page
  // 这里可以调用接口加载对应页的数据
  getData()
}
const tableData = ref([])

// 列配置
const tableColumns = ref([
  { title: '编号', dataIndex: 'id', width: 60 },
  { title: '工艺名称', dataIndex: 'processname' },
  { title: '标识', dataIndex: 'identification' },
  { title: '创建时间', dataIndex: 'createtime' },
  { title: '操作', dataIndex: 'action' }
])
const procedureTableData = ref([])

// 列配置
const procedureTableColumns = ref([
  { key: 'id', title: '编号', dataIndex: 'id', width: 60 },
  { key: 'procedurecode', title: '工序编号', dataIndex: 'procedurecode' },
  { key: 'procedurename', title: '工序名称', dataIndex: 'procedurename' },
  { key: 'procedurehours', title: '工时', dataIndex: 'procedurehours' },
  { key: 'requirement', title: '工序要求', dataIndex: 'requirement' },
  { key: 'createtime', title: '创建时间', dataIndex: 'createtime' },
])
const stepsInfo = ref([
  { id: 1, text: "", procedureId: 0 },
]);
const openAddModel = () => {
  isAdd.value = true
  getProceduce()
  isOperate.value = true
}
const handleEdit = (item) => {
  axios.get("/api/process/isupdate?id=" + item.id).then(r => {
    console.log(r);

    if (r.data.Code == "200") {
      getProceduce()
      isOperate.value = true
      addInfo.value = {
        id: item.id,
        processcode: item.processcode,
        processname: item.processname,
        description: item.description,
      }
      axios.get("/api/procedure/selectids?ids=" + item.procedurelist).then(res => {
        if (res.data.Code == "200") {
          var stepList = []
          res.data.Data.forEach((i, index) => {
            stepList.push({ id: index + 1, text: "编号为：" + i.procedurecode + "的工序：" + i.procedurename, procedureId: i.id })
          })
          stepsInfo.value = stepList
          defaultIds.value = [stepList[0].procedureId]
        }
      })
    } else {
      Message.error(r.data.Msg)
    }
  })


}
const infoInit = () => {
  isOperate.value = false
  isAdd.value = false
  addInfo.value = {}
  defaultIds.value = []
  stepsInfo.value = [{ id: 1, text: "", procedureId: 0 }]
  currentIndex.value = 0
}
const handleConfirm = () => {
  if (!addInfo.value.isAutoCode) {
    if (!addInfo.value.processcode || addInfo.value.processcode == "") {
      Message.warn('请输入工序编号')
      return
    }
  }
  if (!addInfo.value.processname || addInfo.value.processname == "") {
    Message.warn("请输入工艺名称")
    return
  }
  // const unselectedIndex = stepsInfo.value.findIndex(item =>
  //   item.procedureId == null || item.procedureId == 0
  // );
  var nullId = -1
  var procedureIds = []
  stepsInfo.value.forEach((item, index) => {
    if (item.procedureId == null || item.procedureId == 0) {
      nullId = index
    }
    procedureIds.push(item.procedureId)
  })

  // 如果存在未选择的节点，提示并终止执行
  if (nullId != -1) {
    Message.warn("请为第" + (nullId + 1) + "个流程选择工序");
    return; // 这里的return会终止整个函数的执行，不再往下走
  }

  const hasDuplicate = new Set(procedureIds).size !== procedureIds.length;

  if (hasDuplicate) {
    const isConfirmed = window.confirm("存在重复的工序,确定要提交吗？");
    if (!isConfirmed) {
      return
    }
  }

  if (isAdd.value) {
    axios.post("/api/process/save", {
      processcode: addInfo.value.processcode,
      processname: addInfo.value.processname,
      description: addInfo.value.description,
      procedurelist: stepsInfo.value.map(item => item.procedureId).join(",")
    }).then(res => {
      if (res.data.Code == "200") {
        Message.success('添加成功')
        infoInit()
        getData()
      } else {
        Message.warn(res.data.Msg)
      }
    })
  } else {
    axios.post("/api/process/updatebyid", {
      id: addInfo.value.id,
      processcode: addInfo.value.processcode,
      processname: addInfo.value.processname,
      description: addInfo.value.description,
      procedurelist: stepsInfo.value.map(item => item.procedureId).join(",")
    }).then(res => {
      if (res.data.Code == "200") {
        Message.success('修改成功')
        infoInit()
        getData()
      } else {
        Message.warn(res.data.Msg)
      }
    })
  }

}
const handleDelete = (item) => {
  axios.get("/api/process/delete?id=" + item.id).then(res => {
    if (res.data.Code == "200") {
      Message.error('删除成功')
      getData()
    } else {
      Message.warn(res.data.Msg)

    }
  })
}
const handleSelectChange = (selectedIds) => {
  if (procedureTableData.value.length > 0) {
    if (selectedIds.length != 0 && selectedIds.length) {
      var data = procedureTableData.value.find(item => item.id == selectedIds[0])
      stepsInfo.value[currentIndex.value].text = "编号为：" + data.procedurecode + "的工序：" + data.procedurename
      stepsInfo.value[currentIndex.value].procedureId = selectedIds[0]
    }

  }

}
const handleNodeSelected = () => {
  var id = stepsInfo.value[currentIndex.value].procedureId
  if (id != undefined && id != 0) {
    defaultIds.value = [stepsInfo.value[currentIndex.value].procedureId]
  } else {
    defaultIds.value = []
  }

}
const addCancel = () => {
  isAdd.value = false
  isOperate.value = false
  addInfo.value = {}
  stepsInfo.value = [
    { id: 1, text: "", procedureId: 0 },
  ]
  defaultIds.value = []
}
const resetSearch = () => {
  searchInfo.value = { processName: '' }
  getData()
}
const getProceduce = () => {
  var url = '/api/procedure/select?pageNum=' + pageData.value.currentPage + "&pageSize=" + pageData.value.pageSize
  axios.get(url).then(res => {
    procedureTableData.value = res.data.Data.records
    procedurePageData.value = {
      currentPage: procedurePageData.value.currentPage === undefined ? 1 : procedurePageData.value.currentPage,
      total: res.data.Data.total,
      pageSize: res.data.Data.size,
    }

  })
}
const getData = () => {
  var url = '/api/process/select?pageNum=' + pageData.value.currentPage + "&pageSize=" + pageData.value.pageSize
  if (searchInfo.value.processName !== '') {
    url = url + "&processName=" + searchInfo.value.processName
  }
  axios.get(url).then(res => {
    console.log(res.data);

    tableData.value = res.data.Data.records
    pageData.value = {
      currentPage: pageData.value.currentPage === undefined ? 1 : pageData.value.currentPage,
      total: res.data.Data.total,
      pageSize: res.data.Data.size,
    }

  })
}

onMounted(() => {
  getData()

});
</script>
<template>
  <!-- 外层容器添加 h-full 和 flex 布局 -->
  <div class="bg-white w-full h-full pt-[40px] px-[40px] text-base flex flex-col">
    <!-- 列表展示区域 -->
    <div v-if="!isOperate" class="w-full flex-1 flex flex-col">
      <!-- 搜索区域 -->
      <div class="flex justify-start items-center mb-6">
        <InputText type="text" label="工艺名称" placeholder="请输入工艺名称" class="w-[300px] mr-[20px]"
          v-model="searchInfo.processName" label-width="60px" />
        <Button type="primary" content="查询" class="mr-[20px]" @click="getData">
          <template #icon>
            <IconSvg name="search" class="w-[18px] h-[18px]"></IconSvg>
          </template>
        </Button>
        <Button content="重置" class="mr-[20px]" @click="resetSearch">
          <template #icon>
            <IconSvg name="refresh" class="w-[15px] h-[15px]"></IconSvg>
          </template>
        </Button>
      </div>

      <!-- 表格内容区域 - 使用 flex-1 实现自适应高度 -->
      <div class="flex-1 overflow-hidden flex flex-col">
        <div class="flex justify-start items-center mb-4">
          <Button type="primary" content="新增" class="mr-[20px]" @click="openAddModel" v-perm="'process:add'">
            <template #icon>
              <IconSvg name="add" class="w-[18px] h-[18px]"></IconSvg>
            </template>
          </Button>
        </div>

        <!-- 表格容器添加 overflow-auto 实现滚动 -->
        <div class="flex-1 overflow-auto mb-4">
          <DataTable :dataSource="tableData" :columns="tableColumns" class="h-full">
            <template #action="{ item }">
              <a @click="handleEdit(item)" class="text-[#165dff] cursor-pointer" v-perm="'process:edit'">编辑</a>
              <a @click="handleDelete(item)" class="ml-2 text-red-500 cursor-pointer" v-perm="'process:delete'">删除</a>
            </template>
          </DataTable>
        </div>
      </div>

      <!-- 分页区域固定在底部 -->
      <div class="flex justify-end items-center my-4  pt-4">
        <label class="font-medium">共{{ pageData.total }}条</label>
        <PaginationBasic :total="pageData.total" :page-size="pageData.pageSize" v-model:current="pageData.currentPage"
          @onPageChange="handlePageChange" />
      </div>
    </div>

    <!-- 操作表单区域 -->
    <div v-if="isOperate" class="flex-1 overflow-auto">
      <p class="text-[18px] font-medium mb-[20px]">
        {{ isAdd ? '添加工艺' : '编辑工艺' }}
      </p>
      <div class="flex flex-col gap-[20px] pb-[20px]">
        <TextDivider text="基本信息" lineStyle="dashed" lineColor="black" align="left" leftOffset="50px"
          text-color="black" />
        <div class="flex" v-if="isAdd">
          <InputText type="text" label="工序编号" class="w-[500px]" v-model="addInfo.processcode" label-width="80px"
            align="right" :required="true" v-if="!addInfo.isAutoCode" />
          <InputCheckbox label="工序编号" labelWidth="80px" align="right" :required="true" v-model="addInfo.isAutoCode"
            v-if="addInfo.isAutoCode">
            <template #text>
              自动生成编号
            </template>
          </InputCheckbox>
          <InputCheckbox v-model="addInfo.isAutoCode" v-if="!addInfo.isAutoCode">
            <template #text>
              自动生成编号
            </template>
          </InputCheckbox>
        </div>
        <InputText type="text" label="工艺名称" class="w-[500px]" v-model="addInfo.processname" label-width="80px"
          align="right" :required="true" />
        <Textarea type="text" label="工艺描述" class="w-[500px]" v-model="addInfo.description" label-width="80px"
          align="right" />
        <TextDivider text="工艺流程" lineStyle="dashed" lineColor="black" align="left" leftOffset="50px"
          text-color="black" />
        <div class="italic text-[12px]">*勾选工序到工艺流程</div>
        <Flow direction="vertical" v-model="stepsInfo" v-model:selectedIndex="currentIndex"
          @nodeSelected="handleNodeSelected">
          <template #content="{ node }">
            {{ node.text }}
          </template>
        </Flow>
        <TextDivider text="工序信息" lineStyle="dashed" lineColor="black" align="left" leftOffset="50px"
          text-color="black" />
        <!-- 嵌套表格区域 -->
        <div>
          <DataTable :dataSource="procedureTableData" :columns="procedureTableColumns" :showCheckbox="true"
            :isSingleSelect="true" @update:selectedIds="handleSelectChange" :default-selected-ids="defaultIds"
            class="mb-4">
            <template #procedurehours="{ item }">
              {{ item.procedurehours + "秒" }}
            </template>
          </DataTable>

          <div class="flex justify-end items-center">
            <label class="font-medium">共{{ procedurePageData.total }}条</label>
            <PaginationBasic :total="procedurePageData.total" :page-size="procedurePageData.pageSize"
              v-model:current="procedurePageData.currentPage" @onPageChange="handlePageProcessChange" />
          </div>
        </div>

        <!-- 按钮区域固定在底部 -->
        <div class="flex justify-end items-center mt-6 pt-4 ">
          <Button content="取消" class="mr-[20px]" @click="addCancel">
          </Button>
          <Button type="primary" content="确认" class="mr-[20px]" @click="handleConfirm">
          </Button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped></style>